from PySide6.QtCore import Signal, Qt, QRect, QSize
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QStyleOptionButton, QStyle, QTableWidget, QFrame, \
    QHBoxLayout, QTableWidgetItem, QVBoxLayout, QWidget
from qfluentwidgets import TableWidget, TransparentToolButton, FluentIcon, ComboBox, CheckBox


class Table(TableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)  # 设置选择行为，以行为单位
        self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)  # 设置选择模式，选择单行
        self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.verticalHeader().hide()
        self.setBorderVisible(True)
        self.setBorderRadius(8)
        self.setWordWrap(False)
        self.setAlternatingRowColors(True)
        self.setFocusPolicy(Qt.NoFocus)
        horizontalHeader = self.horizontalHeader()
        horizontalHeader.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        horizontalHeader.setDefaultAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)
        # horizontalHeader.setSectionResizeMode(1, QHeaderView.ResizeMode.Interactive)
        verticalHeader = self.verticalHeader()
        verticalHeader.setSectionResizeMode(QHeaderView.ResizeMode.Fixed)


class TableFrame(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.row_list = []
        self._headers = []
        self.initUI()

    def initUI(self):
        self.vBox = QVBoxLayout(self)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(0)

        self.tableView = Table()

        self.vBox.addWidget(self.tableView)

    def addItem(self, data: list):
        self.row_list.append(data)
        self._loadData()

    def addItems(self, data: list):
        self.row_list += data
        self._loadData()

    def deleteRow(self):
        button = self.sender()
        if button:
            row = self.tableView.indexAt(button.parent().pos()).row()
            self.row_list.pop(row)
            self.tableView.removeRow(row)

    def clearContents(self):
        self.row_list = []
        self._loadData()
        return self.tableView.clearContents()

    def _loadData(self):
        """
        重新加载数据
        """
        self.tableView.setRowCount(len(self.row_list))
        for index, value in enumerate(self.row_list):
            for i, v in enumerate(value):
                item = QTableWidgetItem(v)
                item.setToolTip(v)
                item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.tableView.setItem(index, i, item)
            self.tableView.setRowHeight(index, 40)
            self.tableView.setCellWidget(index, len(self._headers) - 1, self.centerButton())

    def setHeaders(self, headers: list):
        headers.append('操作')
        self.tableView.setColumnCount(len(headers))
        self.tableView.setHorizontalHeaderLabels(headers)
        self._headers = headers

    def centerButton(self):
        widget = QFrame()
        hBox = QHBoxLayout(widget)
        hBox.setContentsMargins(0, 0, 0, 0)
        hBox.setSpacing(0)
        hBox.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)

        self.but = TransparentToolButton()
        self.but.setFixedSize(18, 18)
        self.but.setIcon(FluentIcon.CLOSE)
        self.but.clicked.connect(self.deleteRow)
        self.but.setToolTip('删除')
        hBox.addWidget(self.but, 0, Qt.AlignmentFlag.AlignCenter)
        return widget

    def getHeaders(self):
        return self._headers

    def getRowValues(self, row):
        # 行值
        value = []
        for i in range(self.tableView.columnCount()):
            item = self.tableView.item(row, i)
            value.append(item.text())
        return value

    def getColumnValues(self, column):
        # 列值
        value = []
        for i in range(self.tableView.rowCount()):
            item = self.tableView.item(i, column)
            value.append(item.text())
        return value

    def getColumnWidgetText(self, column):
        value = []
        for i in range(self.tableView.rowCount()):
            item = self.tableView.cellWidget(i, column)
            if type(item).__name__ == 'ComboBox':
                item: ComboBox
                text = item.currentText()
            elif type(item).__name__ == 'QFrame':
                item: QFrame
                checkBox: CheckBox = item.findChild(CheckBox)
                text = checkBox.isChecked()

            else:
                text = item.text()
            value.append(text)
        return value

    def setCellWidget(self, row: int, column: int, widget: QWidget):
        self.tableView.setCellWidget(row, column, widget)

    def clear(self):
        self.row_list = []
        self._loadData()
        # self.tableView.clear()

    def columnCount(self):
        return self.tableView.columnCount()

    def rowCount(self):
        return self.tableView.rowCount()
